package com.sdwl.brcl.service.impl;

import cn.hyperchain.sdk.common.utils.Encoder;
import cn.hyperchain.sdk.exception.RequestException;
import cn.hyperchain.sdk.provider.DefaultHttpProvider;
import cn.hyperchain.sdk.provider.ProviderManager;
import cn.hyperchain.sdk.service.ContractService;
import cn.hyperchain.sdk.service.ServiceManager;
import cn.hyperchain.sdk.transaction.Transaction;
import com.google.gson.Gson;
import com.sdwl.brcl.domain.UserAccount;
import com.sdwl.brcl.service.ChainSysService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.function.ServerResponse;

import java.io.IOException;
import java.io.InputStream;

@Service
public class ChainSysServiceImpl implements ChainSysService {
    @Override
    public String createContract(String account, String url, MultipartFile multipartFile, String contractAddress) throws RequestException, IOException {
        UserAccount userAccount = new Gson().fromJson(account, UserAccount.class);
        DefaultHttpProvider provider = new DefaultHttpProvider.Builder().setUrl(url).build();
        ProviderManager providerManager = ProviderManager.createManager(provider);
        ContractService contractService = ServiceManager.getContractService(providerManager);
        InputStream payload = multipartFile.getInputStream();
        Transaction transaction;
        // 传入合约地址，则升级合约
        if (StringUtils.isNotBlank(contractAddress)) {
            transaction = new Transaction.HVMBuilder(userAccount.getAddress()).upgrade(contractAddress, Encoder.encodeDeployJar(payload)).build();
            transaction.sign(ServiceManager.getAccountService(providerManager).fromAccountJson(account));
            return contractService.maintain(transaction).send().polling().getMessage();
        } else {
            transaction = new Transaction.HVMBuilder(userAccount.getAddress()).deploy(payload).build();
            transaction.sign(ServiceManager.getAccountService(providerManager).fromAccountJson(account));
            return contractService.deploy(transaction).send().polling().getContractAddress();
        }
    }
}
